#include <array>
#include <iostream>
#include <stdexcept>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

class EchoClient
{
  public:
    explicit EchoClient(uint16_t port) : sin{}
    {
        if (fd_ = ::socket(AF_INET, SOCK_DGRAM, 0); fd_ < 0)
        {
            throw std::runtime_error(strerror(errno));
        }
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);
        sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        if (Connect() < 0)
        {
            throw std::runtime_error(strerror(errno));
        }
    }

    void Echo()
    {
        while (true)
        {
            std::string sendBuf{};
            std::array<char, BUFSIZ> recvBuf{};
            std::cin >> sendBuf;
            if (sendBuf == "exit")
            {
                Send({});
                break;
            }
            Send(sendBuf);
            Recv(recvBuf);
            std::cout << "Server said: " << recvBuf.data() << '\n';
        }
    }

    ~EchoClient()
    {
        ::close(fd_);
    }

  private:
    int Connect()
    {
        return ::connect(fd_, &sa, sizeof(sin));
    }

    ssize_t Send(const std::string& buf)
    {
        return ::write(fd_, buf.c_str(), buf.size());
    }

    ssize_t Recv(std::array<char, BUFSIZ>& buf)
    {
        return ::recv(fd_, buf.data(), buf.size() - 1, 0);
    }

  private:
    int fd_;
    union
    {
        sockaddr_in sin;
        sockaddr sa;
    };
};

using namespace std;
int main(int argc, char** argv)
{
    EchoClient cli(12345);
    cli.Echo();
    return 0;
}